package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.Toast;

import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.TipEntity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.beans.BGchat;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 聊天管理
 */
public class ChatMgrActivity extends BaseSwipeBackActivity implements CompoundButton.OnCheckedChangeListener, MyDialog.DialogItemClickListener {

    @BindView(R.id.pre_v_back)
    ImageView pre_v_back;
    @BindView(R.id.head_image)
    ImageView head_image;
    @BindView(R.id.create_group)
    ImageView create_group;
    @BindView(R.id.clear_chat_message)
    LinearLayout clear_chat_message;
    @BindView(R.id.is_not_disturb)
    Switch isNotDisturb;
    @BindView(R.id.is_top_chat)
    Switch isTopChat;
    @BindView(R.id.find_all_chat_message)
    LinearLayout find_all_chat_message;
    @BindView(R.id.chat_bg)
    LinearLayout chat_bg;
    @BindView(R.id.linear_omplaint)
    LinearLayout linear_omplaint;
    private UserEntivity userEntivity;

    private PGService mPGservice;
    ImFriendEntivity mFriendEntivity;//
    private int receiveTip = 0;
    private boolean isChangeTr = true;
    private Long destid;

    private static final int SDK_PERMISSION_REQUEST = 127;
    public final static int CHOSE_IMG = 101;
    private String choesimgpath;
    private static final String TAG = "ChatMgrActivity";

    @Override
    public int getContentViewId() {
        return R.layout.activity_chat_mgr;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.chat_info);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
        destid = getIntent().getLongExtra("destid", 0);
//        EventBus.getDefault().register(this);
        mFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, destid);
        userEntivity = ToolsUtils.getUser();
        List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", destid + "", Constant.FROM_TYPE_MAM + "");
        for (int i = 0; i < tipEntities.size(); i++) {
            TipEntity tipEntity = tipEntities.get(i);
            if (tipEntity.getDestId().equals(destid + "") && tipEntity.getUserId().equals(userEntivity.getId() + "") && tipEntity.getDestType() == Constant.FROM_TYPE_MAM) {//存在了，表示现在是取消置顶聊天
                isTopChat.setChecked(true);//设置置顶了需要显示
            }
        }

        isNotDisturb.setOnCheckedChangeListener(this);
        isTopChat.setOnCheckedChangeListener(this);

        if (null != mFriendEntivity) {
            GlideUtils.loadHeadCircularImage(getApplicationContext(), mFriendEntivity.getHeadUrl(), head_image);
            switch (Integer.parseInt("".equals(mFriendEntivity.getReceiveTip()) ? "1" : (null == mFriendEntivity.getReceiveTip() ? "1" : mFriendEntivity.getReceiveTip()))) {
                case 0:
                    isChangeTr = false;
                    isNotDisturb.setChecked(true);
                    break;
                case 1:
                    isNotDisturb.setChecked(false);
                    break;
            }
        }
    }

    /**
     * 设置消息免打扰
     * 免打扰设置了以后，消息列表会实时更新，消息列表和底部的小红点不显示，目前没有声音和振动功能所以不修改
     */
    public void setIgnore(String groupId) {
        mPGservice.setIgonre(groupId, "1", String.valueOf(receiveTip), ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity data) {
                new ToastUtils().showSingleToast(data.getInfo());
                //
                ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, destid);
                if (null != imFriendEntivity) {
                    imFriendEntivity.setReceiveTip("" + receiveTip);
//                    ImFriendEntivity.update(imFriendEntivity);
                    imFriendEntivity.save();
                }
            }
        });
    }

    /**
     * 设置置顶
     *
     * @param destId
     */
    public void setTop(final String destId) {
        showProgress(getResources().getString(R.string.setting));
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPGservice.setTop(destId, Constant.FROM_TYPE_MAM + "", userEntivity.getId() + "")
                .subscribe(new AbsAPICallback<ValidateEntivity>() {
                               @Override
                               protected void onResultError(ApiException ex) {
                                   new ToastUtils().showSingleToast(ex.getDisplayMessage());
                               }

                               @Override
                               public void onNext(ValidateEntivity data) {
                                   new ToastUtils().showSingleToast(data.getInfo());
                                   List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid =? and uniqueness=?", userEntivity.getId() + "", destId, "_");
                                   for (int i = 0; i < messageEntivities.size(); i++) {
                                       MessageEntivity messageEntivity = messageEntivities.get(i);
                                       messageEntivity.setIstop(Constant.TOP_MAN);
                                       messageEntivity.save();
                                   }
                                   List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", destId, Constant.FROM_TYPE_MAM + "");
                                   if (tipEntities.size() > 0) {
                                       /** 这个地方是更新了是否置顶，由于MessageFragment中获取列表的形式，单独修改置顶比较麻烦，这里只能用这个了 */
                                       EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                                       hideProgress();
                                       return;
                                   }
                                   //不存在置顶聊天，需要加入到置顶
                                   TipEntity tipEntity = new TipEntity();
                                   tipEntity.setDestId(destId);
                                   tipEntity.setUserId(userEntivity.getId() + "");
                                   tipEntity.setDestType(Constant.FROM_TYPE_MAM);
                                   tipEntity.save();
                                   /** 这个地方是更新了是否置顶，由于MessageFragment中获取列表的形式，单独修改置顶比较麻烦，这里只能用这个了 */
                                   EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                                   hideProgress();
                               }
                           }
                );
    }

    /**
     * 取消置顶
     */
    private void cancleTop(final String destId) {
        showProgress(getString(R.string.setting));
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPGservice.cancleTop(destId, "1", userEntivity.getId() + "").subscribe(new AbsAPICallback<ValidateEntivity>() {
                                                                                   @Override
                                                                                   protected void onResultError(ApiException ex) {
                                                                                       showToast(ex.getDisplayMessage());
                                                                                   }

                                                                                   @Override
                                                                                   public void onNext(ValidateEntivity validateEntivity) {

                                                                                       List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", destId, Constant.FROM_TYPE_MAM + "");
                                                                                       for (int i = 0; i < tipEntities.size(); i++) {
                                                                                           tipEntities.get(i).delete();
                                                                                       }
                                                                                       List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid =? and uniqueness=?", userEntivity.getId() + "", destId, "_");
                                                                                       for (int i = 0; i < messageEntivities.size(); i++) {
                                                                                           MessageEntivity messageEntivity = messageEntivities.get(i);
                                                                                           messageEntivity.setIstop(Constant.TOP_NOT_MAN);
                                                                                           messageEntivity.save();
                                                                                       }
                                                                                       /** 这个地方是更新了是否置顶，由于MessageFragment中获取列表的形式，单独修改置顶比较麻烦，这里只能用这个了 */
                                                                                       EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                                                                                       //修改本地好友数据
                                                                                       hideProgress();
                                                                                       showToast(validateEntivity.getInfo());
                                                                                   }
                                                                               }

        );
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (isChecked) {
            receiveTip = 0;
        } else {
            receiveTip = 1;
        }
        switch (compoundButton.getId()) {
            case R.id.is_top_chat:  //置顶

                if (isTopChat.isChecked()) {
                    setTop(mFriendEntivity.getId() + "");
                } else {
                    cancleTop(mFriendEntivity.getId() + "");
                }
                break;
            case R.id.is_not_disturb:   //免打扰
                if (isChangeTr) {
                    setIgnore(null == mFriendEntivity ? "32" : "" + mFriendEntivity.getId());
                } else {
                    isChangeTr = true;
                }
                break;
        }
    }

    @OnClick({R.id.create_group, R.id.head_image, R.id.pre_v_back, R.id.find_all_chat_message, R.id.clear_chat_message, R.id.chat_bg
            , R.id.linear_omplaint})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.create_group://加好友创建群组
                Bundle bundleg = new Bundle();
                bundleg.putInt("goGroup", 1);
                startActivityForResult(SelecteGroupFriendActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundleg);
                break;
            case R.id.clear_chat_message://清除聊天记录

                Dialog dialog = MyDialog.ShowDialog(this, null, new String[]{getResources().getString(R.string.clean_message_ok)}, this);
                dialog.show();
                break;
            case R.id.head_image://

//                Bundle bundle = new Bundle();
//                bundle.putSerializable("imageUrl", null == mFriendEntivity ? "" : mFriendEntivity.getHeadUrl());
//                startActivity(BagImageActivity.class, bundle);

//                if (null!=mFriendEntivity){
                ArrayList<String> imageList = new ArrayList<>();
                imageList.add(null == mFriendEntivity ? "" : mFriendEntivity.getHeadUrl());
                Intent intentB = new Intent(getApplicationContext(), ImageViewActivity.class);
                intentB.putStringArrayListExtra("images", imageList);
                intentB.putExtra("clickedIndex", 0);
                startActivity(intentB);
//                }

                break;
            case R.id.pre_v_back://
                scrollToFinishActivity();
                break;
            case R.id.find_all_chat_message://
                Long id = mFriendEntivity.getId();
//                Bundle bundle1 = new Bundle();
//                bundle1.putLong("uid", id);
//                bundle1.putString("startMsgId", "");
//                bundle1.putInt("isGroup", 1);
                Intent intent = new Intent(this, ChatHistoryActivity.class);
                intent.putExtra("uid", id + "");
                intent.putExtra("startMsgId", "");
                intent.putExtra("isGroup", 1);
                startActivity(intent);
                break;
            case R.id.chat_bg://
                MyDialog.showBGDialog(ChatMgrActivity.this, handler);
                break;
            case R.id.linear_omplaint://
                MyWebViewManageActivity.start(ChatMgrActivity.this, 3, "http://samim.huiwork.com/wap/reportFriend", "" + mFriendEntivity.getId(), 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.MESSAGE_MAIN_GO_GROUP_RESULT:
                if (resultCode == Constant.MESSAGE_MAIN_GO_GROUP_RESULT) {
                    setResult(Constant.MESSAGE_MAIN_GO_GROUP_RESULT);
                    scrollToFinishActivity();
                }
                break;

            case CHOSE_IMG:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size() > 0) {
                        choesimgpath = stringArrayListExtra.get(0);
                        Log.i("info", "返回的路径s==" + choesimgpath);
//                        Bitmap bitmap = PictureUtil.getSmallBitmap(choesimgpath);
                        LookBGImage.startActivity(ChatMgrActivity.this, choesimgpath, "" + destid, 1);
//                        Bitmap bitmap = BitmapFactory.decodeFile(choesimgpath, new BitmapFactory.Options());
//                        final File file = new File(choesimgpath);
//                        if (file.exists()){
////                            Uri uri = Uri.fromFile(file);
////                            ToolsUtils.cropImageUri(this,uri,600,600,3333);
//                        }else {
//                            ToolsUtils.showToast(PrivacyActivity.this,"所选文件不存在");
//                        }
                    }
                }

                break;
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 106:
                    getPersimmions();
                    break;
                case 107:
                    try {
                        List<BGchat> list = BGchat.find(BGchat.class, "creatid=? and sessionid=?", new String[]{ToolsUtils.getMyUserId(), "" + destid});
                        if (null != list && list.size() > 0) {
                            BGchat mBGsetAll = list.get(0);
                            mBGsetAll.setBgchat("");
                            mBGsetAll.save();
                        } else {
                            BGchat mBGsetAll = new BGchat();
                            mBGsetAll.setCreatid(ToolsUtils.getMyUserId());
                            mBGsetAll.setSessionid("" + destid);
                            mBGsetAll.setBgchat("");
                            mBGsetAll.save();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    showToast(getResources().getString(R.string.set_finish));
                    break;
            }
        }
    };

    @Override
    public void confirm(String result) {
        if (result.equals(getResources().getString(R.string.clean_message_ok))) {
            showProgress(getString(R.string.deletting));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //清空了聊天数据库
                    ImMessage.deleteAll(ImMessage.class, "uniqueness=?", new String[]{ToolsUtils.getMyUserId() + "_" + destid});
                    //清除消息列表数据
                    MessageEntivity.deleteAll(MessageEntivity.class, "fromid=? and destid=? and from_type=?", new String[]{ToolsUtils.getMyUserId() + "", destid + "", Constant.FROM_TYPE_MAM + ""});
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    hideProgress();
                    EventBus.getDefault().post(Constant.BLACK_CLEAR_CHAT_MESSAGE_REFRESH);
                }
            }).start();
        }
    }


    @TargetApi(23)
    protected void getPersimmions() {
        isgo = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0;
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
                pos++;
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)) {
                pos++;
            }
            if (2 == pos) {
                gotoPhoto();
            }
            if (permissions.size() > 0) {
                Log.i(TAG, "getPersimmions: --------001--------");
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        } else {
            gotoPhoto();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        Log.i(TAG, "getPersimmions: --------002--------");
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            Log.i(TAG, "getPersimmions: --------003--------");
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                Log.i(TAG, "getPersimmions: --------004--------");
                return false;
            } else {
                Log.i(TAG, "getPersimmions: --------005--------");
                permissionsList.add(permission);
                return false;
            }
        } else {
            Log.i(TAG, "getPersimmions: --------0011--------");

            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "getPersimmions: --------006--------");
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Log.i(TAG, "getPersimmions: --------007--------");
                Map<String, Integer> perms = new HashMap<String, Integer>();
//                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
//                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                Log.i(TAG, "getPersimmions: --------008--------");
                try {
                    int isgre = 0;
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        isgre++;
                    }
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        isgre++;
                    }
                    if (2 <= isgre) {
                        gotoPhoto();
                    } else {
                        Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                                .show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    boolean isgo = false;

    private void gotoPhoto() {
        if (!isgo) {
            PhotoPickerIntent pt = new PhotoPickerIntent(ChatMgrActivity.this);
            pt.setSelectModel(SelectModel.MULTI);
            pt.setShowCarema(true); // 是否显示拍照， 默认false
            pt.setMaxTotal(1); // 最多选择照片数量，默认为9
            //pt.setImageConfig(conFig);
            startActivityForResult(pt, CHOSE_IMG);
        }
        isgo = true;
    }


}
